import request from "@/utils/request";
import { fetchEventSource } from "@microsoft/fetch-event-source";
class FatalError extends Error {}
class RetriableError extends Error {}

type ResultCallBack = (e: any | null) => void;

export const postStreamChat = (
    author: string,
    data: string,
    Token: string,
    onMessage: ResultCallBack,
    onError: ResultCallBack,
    onClose: ResultCallBack
  )=> {
    const ctrl = new AbortController();
    fetchEventSource(import.meta.env.VITE_APP_BASE_API+"/api/aiserv/answer", {
      method: "POST",
      headers: {
        token:Token,
        "Content-Type": "application/json",
        // "accept": "application/json, text/plain, */*",
      },
      body: JSON.stringify({
        session_code: author,
        question: data,
      }),
      signal: ctrl.signal,
      // 处理响应的数据，该数据是一段一段的 
      onmessage: onMessage,
      // 发生错误后调用
      onerror: (err: any) => {
        onError(err);
      },
       // 连接关闭后处理逻辑
      onclose: () => {
        onClose(null);
      },
      onopen: async (response: any) => {
        console.log(response);
        
        if (response.ok) {
          return;
        } 
      },
    });
  };